package org.ns.socket.client;

import org.ns.socket.client.codec.SocketDecodeHandler;
import org.ns.socket.client.codec.SocketEncodeHandler;
import org.ns.socket.client.handler.SocketHandler;
import org.ns.socket.client.handler.SocketReaderHandler;

import java.io.IOException;
import java.util.concurrent.ExecutorService;

public class Client {

    private ExecutorService workerThread; // 业务执行的线程
    private SocketHandler socketHandler;  // socket 处理实现

    private SocketDecodeHandler socketDecodeHandler; // 解码数据
    private SocketEncodeHandler socketEncodeHandler; // 编码数据
    private SocketReaderHandler socketReaderHandler; // socket 的数据读取处理


    public Client(ExecutorService workerThread, Class<? extends SocketHandler> handler) throws ClientException{
        try {
            this.workerThread = workerThread;
            socketHandler = handler.newInstance();
        } catch (Exception e) {
            throw new ClientException(e);
        }
    }

    public Client setSocketDecodeHandler(SocketDecodeHandler socketDecodeHandler) {
        this.socketDecodeHandler = socketDecodeHandler;
        return this;
    }

    public Client setSocketEncodeHandler(SocketEncodeHandler socketEncodeHandler) {
        this.socketEncodeHandler = socketEncodeHandler;
        return this;
    }

    public Client setSocketReaderHandler(SocketReaderHandler socketReaderHandler) {
        this.socketReaderHandler = socketReaderHandler;
        return this;
    }

    public void connect(String host, int port) throws IOException {
        socketHandler.setWorkerThread(workerThread);
        socketHandler.setSocketDecodeHandler(socketDecodeHandler);
        socketHandler.setSocketEncodeHandler(socketEncodeHandler);
        socketHandler.setSocketReaderHandler(socketReaderHandler);
        socketHandler.connect(host, port);
    }

    public void write(Object msg) {
        socketHandler.write(msg);
    }

    public void close()throws IOException {
        socketHandler.close();
    }
}
